/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Conexion.Conexion;
import Datos.Personal;
import Datos.Ruta;
import Negocio.Negocio;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Mufase
 */
public class IngresoRuta extends javax.swing.JDialog {

    /**
     * Creates new form IngresoRuta
     */
    public IngresoRuta(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        llenarComboboxCamion();
        llenarComboboxCarga();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtConductor = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtAux = new javax.swing.JTextField();
        btnIngresar = new javax.swing.JButton();
        btnConsultar = new javax.swing.JButton();
        btnVolver = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        txtOrigen = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtDestino = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        cmbCamion = new javax.swing.JComboBox();
        cmbCarga = new javax.swing.JComboBox();

        jLabel2.setText("jLabel2");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ingreso de Ruta");
        setResizable(false);

        jLabel1.setText("Camion:");

        jLabel3.setText("CodDesp Carga:");

        jLabel4.setText("Conductor:");

        txtConductor.setEnabled(false);

        jLabel5.setText(" Aux:");

        txtAux.setEnabled(false);

        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        btnVolver.setText("Volver");
        btnVolver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVolverActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel7.setText("Origen:");

        txtOrigen.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtOrigenKeyTyped(evt);
            }
        });

        jLabel8.setText("Destino:");

        txtDestino.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDestinoKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtOrigen, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(txtDestino)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        cmbCamion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCamionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtAux, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtConductor, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbCamion, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(82, 82, 82)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbCarga, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(btnIngresar)
                        .addGap(18, 18, 18)
                        .addComponent(btnConsultar)
                        .addGap(18, 18, 18)
                        .addComponent(btnVolver, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(22, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(cmbCamion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbCarga, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtConductor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtAux, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVolver)
                    .addComponent(btnConsultar)
                    .addComponent(btnIngresar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        // Validar el ingreso de datos
        if (this.cmbCamion.getSelectedItem()=="Seleccione...") {
            JOptionPane.showMessageDialog(this, "Debe seleccionar el Camion", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.cmbCamion.requestFocus();
            return;
        }
        if (this.cmbCarga.getSelectedItem()=="Seleccione...") {
            JOptionPane.showMessageDialog(this, "Debe seleccionar el Codigo", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.cmbCarga.requestFocus();
            return;
        }
        if (this.txtOrigen.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Debe ingresar el Origen", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.txtOrigen.requestFocus();
            return;
        }
        if (this.txtDestino.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Debe ingresar el Destino", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.txtDestino.requestFocus();
            return;
        }
        
        Negocio neg=new Negocio();
        Ruta ruta = new Ruta();
        ruta.setPatenteCamion(String.valueOf(this.cmbCamion.getSelectedItem()));
        ruta.setCodDesCarga(Integer.parseInt(String.valueOf(this.cmbCarga.getSelectedItem())));
        ruta.setRutConductor(this.txtConductor.getText().trim());
        ruta.setRutAux(this.txtAux.getText().trim());
        ruta.setOrigen(this.txtOrigen.getText().trim());
        ruta.setDestino(this.txtDestino.getText().trim());
        neg.ingresarRuta(ruta);
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void btnVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVolverActionPerformed
        int opcion = 0;
        opcion = JOptionPane.showConfirmDialog(this, "¿Desea volver al Menu Principal?", "Salir de Ingreso de Ruta",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION) {
            this.dispose();
        }
    }//GEN-LAST:event_btnVolverActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        Negocio neg = new Negocio();

        Ruta ruta = neg.buscarRuta(String.valueOf(this.cmbCamion.getSelectedItem()));

        if (ruta.getPatenteCamion().trim().length() != 0) {
            this.cmbCamion.setSelectedItem(ruta.getPatenteCamion());
            this.txtConductor.setText(ruta.getRutConductor());
            this.txtAux.setText(ruta.getRutAux());
            this.cmbCarga.setSelectedItem(ruta.getCodDesCarga());
            this.txtOrigen.setText(ruta.getOrigen());
            this.txtDestino.setText(ruta.getDestino());
        } else {
            JOptionPane.showMessageDialog(this, "Ruta no existe", "Error de Ingreso", JOptionPane.ERROR_MESSAGE);
            this.cmbCamion.requestFocus();
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void cmbCamionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCamionActionPerformed
        llenarAuxiliarConductor(String.valueOf(this.cmbCamion.getSelectedItem()));
    }//GEN-LAST:event_cmbCamionActionPerformed

    private void txtOrigenKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtOrigenKeyTyped
         if (this.txtOrigen.getText().trim().length() > 15) {
            evt.consume();
        }
    }//GEN-LAST:event_txtOrigenKeyTyped

    private void txtDestinoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDestinoKeyTyped
      if (this.txtDestino.getText().trim().length() > 15) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDestinoKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IngresoRuta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IngresoRuta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IngresoRuta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IngresoRuta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                IngresoRuta dialog = new IngresoRuta(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JButton btnVolver;
    private javax.swing.JComboBox cmbCamion;
    private javax.swing.JComboBox cmbCarga;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtAux;
    private javax.swing.JTextField txtConductor;
    private javax.swing.JTextField txtDestino;
    private javax.swing.JTextField txtOrigen;
    // End of variables declaration//GEN-END:variables

    private void llenarComboboxCamion() {
        Conexion cnn = new Conexion();

        cnn.setDriver("com.mysql.jdbc.Driver");
        cnn.setUrl("jdbc:mysql://localhost:3306/flota");

        cnn.setNombreBaseDatos("Flota");
        cnn.setNombreTabla("Camion");
        cnn.setPassword("");
        cnn.setUser("root");

        cnn.setEsSelect(true);

        cnn.setSentenciaSQL("select idCamion from " + cnn.getNombreTabla());

        cnn.conectar();
        cmbCamion.addItem("Seleccione...");
        try {
            while (cnn.getRst().next()) {

                cmbCamion.addItem(cnn.getRst().getString("idCamion"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(RegistroCamiones.class.getName()).log(Level.SEVERE, null, ex);
        }

        cnn.cerrarConexion();
    }

    public void llenarAuxiliarConductor(String camion) {
        Negocio neg = new Negocio();
        Conexion cnn = new Conexion();

        if (camion == "Seleccione...") {
            this.txtConductor.setText("");
            this.txtAux.setText("");
        } else {
            cnn.setDriver("com.mysql.jdbc.Driver");
            cnn.setUrl("jdbc:mysql://localhost:3306/flota");
            cnn.setNombreBaseDatos("Flota");
            cnn.setNombreTabla("Camion");
            cnn.setPassword("");
            cnn.setUser("root");

            cnn.setEsSelect(true);

            cnn.setSentenciaSQL("select Conductor_idConductor,Auxiliar_idAuxiliar from " + cnn.getNombreTabla() + " where idCamion = '" + camion + "'");
            System.out.println(cnn.getSentenciaSQL());
            cnn.conectar();
            try {
                while (cnn.getRst().next()) {
                    this.txtConductor.setText(cnn.getRst().getString("Conductor_idConductor"));
                    this.txtAux.setText(cnn.getRst().getString("Auxiliar_idAuxiliar"));
                }

            } catch (SQLException ex) {
                Logger.getLogger(RegistroCamiones.class.getName()).log(Level.SEVERE, null, ex);
            }
            cnn.cerrarConexion();
        }
    }

    private void llenarComboboxCarga() { 
        Conexion cnn = new Conexion();
        
        cnn.setDriver("com.mysql.jdbc.Driver");
        cnn.setUrl("jdbc:mysql://localhost:3306/flota");

        cnn.setNombreBaseDatos("Flota");
        cnn.setNombreTabla("Carga");
        cnn.setPassword("");
        cnn.setUser("root");
        
        cnn.setEsSelect(true);
        cnn.setSentenciaSQL("select idCarga from " + cnn.getNombreTabla());
        
        System.out.println(cnn.getSentenciaSQL());
        this.cmbCarga.addItem("Seleccione...");

        cnn.conectar();
        try {
            while (cnn.getRst().next()) {
                this.cmbCarga.addItem(cnn.getRst().getInt("idCarga"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(RegistroCamiones.class.getName()).log(Level.SEVERE, null, ex);
        }
        cnn.cerrarConexion();

    }
}
